﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mime;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BLL;
using Model;
using WebPortal.Models;
using System.Configuration;
using Common;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace WebPortal.Controllers
{
    public class AccountController : Controller
    {
        private static EncrypCode encrypCode = new EncrypCode();
        public ActionResult LogOn()
        {
            //ClearSession();
            return View();
        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="collection">提交信息</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public string LogOn(FormCollection collection)
        {
            string userName = collection["txt_UserName"];
            string pwd = collection["txt_UserPwd"];
            string rd = collection["txt_Randomint"];
            if (Session["img"] != null && Session["img"].ToString() == rd)//验证码
            {
                Session["img"] = "";
                SqlParameter[] pare = new SqlParameter[] { 
                   new SqlParameter("@username", userName), 
                   new SqlParameter("@pwd", pwd) 
               };
                try
                {
                    //检查用户名密码
                    List<Sys_RoleInfo> roleID = SysUserBLL.GetLogin(pare);
                    if (roleID[0].RoleID == "0")
                    {
                        new SysOperationLog(new LoginInfo()).Log("", Request.UserHostAddress, OperationAction.用户登陆, OperationStatus.失败, "登陆失败,用户名或密码错。", userName);
                        return "0";
                    }
                    if (roleID[0].RoleID == "1")
                    {
                        return "1";
                    }
                    if (roleID[0].RoleID == "2")
                    {
                        return "2";
                    }
                    else
                    {
                        //第一次登录初始化
                        SysOperationLog logBll = new SysOperationLog(new LoginInfo());
                        if (logBll.InitLogin())
                        { 
                            string dataBase = ConfigurationManager.AppSettings["DataBase"].ToString();
                            HomeController home = new HomeController();
                            home.CreateETL(dataBase);
                            home.CreateJob(dataBase, "1");
                        }
                        //保存登陆信息
                        Session["MDM_UserName"] = userName;
                        HttpCookie u = new HttpCookie("MDM_UserName") { Value = userName, HttpOnly = true };
                        u.Expires = DateTime.Now.AddDays(1);
                        this.Response.Cookies.Add(u);

                        u = new HttpCookie("MDM_EName", HttpUtility.UrlEncode(roleID[0].Description));
                        u.Expires = DateTime.Now.AddDays(1);
                        this.Response.Cookies.Add(u);

                        u = new HttpCookie("MDM_UserIP", Request.UserHostAddress);
                        u.Expires = DateTime.Now.AddDays(1);
                        this.Response.Cookies.Add(u);

                        logBll.Log("", Request.UserHostAddress, OperationAction.用户登陆, OperationStatus.成功, "登陆成功", userName);
                        return "ok";
                    }
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            else
            {
                return "-1";
            }
        }
        public ActionResult CreateRandom(string time)
        {
            string code = GetRandomint(4);
            Session["img"] = code;
            byte[] bytes = CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 8; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Italic | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 50; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="codeCount">位数</param>
        /// <returns></returns>
        private string GetRandomint(int codeCount)
        {
            Random random = new Random();
            string min = "";
            string max = "";
            for (int i = 0; i < codeCount; i++)
            {
                min += "1";
                max += "9";
            }
            return (random.Next(Convert.ToInt32(min), Convert.ToInt32(max)).ToString());
        }
        /// <summary>
        /// 退出登陆 
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOff()
        {
            ClearSession();
            return RedirectToAction("LogOn", "Account");
        }
        /// <summary>
        /// 清除缓存
        /// </summary>
        public void ClearSession()
        {
            Session.Clear();
            Session.Abandon();
            HttpCookie aCookie;
            string cookieName;
            int limit = Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = Request.Cookies[i].Name;
                aCookie = new HttpCookie(cookieName);
                aCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(aCookie);
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            ClearSession();
            return View(model);
        }

        #region 备份方法-已失效
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
        #endregion
    }
}
